<template name="grainView">
  {{!-- This template is rendered manually using Blaze.renderWithData() for each currently-open
        grain and then injected into .main-content. We do things manually so that we can be
        sure that adding or removing grains from the open grain list does not cause other grains'
        iframes to be re-rendered, losing state. --}}
  {{#with unpackedGrainState}}
    <div class="grain-container {{#if active}}active-grain{{else}}inactive-grain{{/if}}">
    {{#if error}}
      {{#if inMyTrash}}
        {{> grainInMyTrash . }}
      {{else}}
        {{#if inOwnersTrash}}
          {{> grainInOwnersTrash ""}}
        {{else}}{{#if grainOwnerSuspended}}
          {{> grainOwnerSuspended ""}}
        {{else}}
          {{#if unauthorized}}
            {{#if token}}
              {{> revokedShareLink ""}}
            {{else}}
              {{> requestAccess . }}
            {{/if}}
          {{else}}
            {{#if notFound}}
              <p class="grain-not-found grain-interstitial">
                No grain found with ID "{{grainId}}".
              </p>
            {{else}}
               <pre>{{error}}</pre>
            {{/if}}
          {{/if}}
        {{/if}}{{/if}}
      {{/if}}
    {{else}}
    {{#if appOrigin}}
      {{!-- Selenium requires iframes to have an id in order to select them. `id` is only
            used for testing purposes. --}}
      <iframe data-grainid="{{grainId}}" id="{{idPrefix}}grain-frame-{{grainId}}" class="grain-frame" src="{{appOrigin}}/_sandstorm-init?sessionid={{sessionId}}&path={{originalPath}}"></iframe>
      {{#with signinOverlay}}
        {{#modalDialogWithBackdrop class="signin" onDismiss=closeSignInOverlay}}
          {{> loginButtonsDialog label=label accountsUi=globalAccountsUi}}
        {{/modalDialogWithBackdrop}}
      {{/with}}
      {{#if hasNotLoaded}}
        {{> _grainSpinner ""}}
      {{/if}}
    {{else}}
    {{#if interstitial.chooseIdentity}}
      <div class="grain-interstitial">
        <p>With which of your identities would you like to open this grain?</p>
        {{> identityPicker identityPickerData}}
        {{#if interstitial.showIncognito}}
        <button class="incognito-button" data-token="{{token}}">Open in Incognito Mode</button>
        {{/if}}
      </div>
    {{else}}
      {{> _grainSpinner ""}}
    {{/if}}
    {{/if}}
    {{/if}}
    </div>
  {{/with}}
</template>

<template name="grainInMyTrash">
  <div class="grain-interstitial">
    <p>
      This grain is in your trash. You cannot access it unless you restore it to your main list.
    </p>
    <button class="restore-from-trash">Restore to main list</button>
  </div>
</template>

<template name="grainInOwnersTrash">
  <div class="grain-interstitial">
    <p>
      You can no longer access this grain because its owner has moved it to the trash.
    </p>
  </div>
</template>

<template name="grainOwnerSuspended">
  <div class="grain-interstitial">
    <p>
      You can no longer access this grain because its owner's account has been suspended.
    </p>
  </div>
</template>


<template name="wrongIdentity">
  <div class="grain-interstitial">
    <p>
      Access through this URL is restricted to the identity:
    </p>
    {{> identityCardSignInButton identity=recipient unclickedMessage=unclickedMessage}}
  </div>
</template>

<template name="requestAccess">
  <div class="request-access grain-interstitial">
  <p>You do not have permission to access this grain.</p>
  {{#if currentUser}}
    {{#with status}}
      {{#if showButton}}
        <button class="request-access" title="Request access">
          Request Access
        </button>
      {{/if}}
      {{#if chooseIdentity}}
        <p>Requesting access will reveal your identity to the grain owner.</p>
        <p> {{chooseIdentityText}} </p>
        {{> identityPicker identityPickerData}}
      {{/if}}
      {{#if waiting}}
         <p>Sending your request...</p>
      {{/if}}
      {{#if success}}
        <p>
          Your request has been sent. You will receive an email if your request is approved.
        </p>
      {{/if}}
      {{#with error}}
        <p>Your request failed because: {{.}}</p>
      {{/with}}
    {{/with}}
  {{else}}
    Please sign in to request access.
  {{/if}}
  </div>
</template>

<template name="invalidToken">
   <pre> Invalid token: {{token}} </pre>
</template>

<template name="revokedShareLink">
  <p class="grain-interstitial">Sorry, this link has been revoked.</p>
</template>

<template name="grainTitle">
  {{#with fullTitle}}
    <div class="editable" title="Rename" id="grainTitle" tabindex="0">
      {{#if hasSubtitle}}
        <div class="main-title">{{title}}</div>
        <div class="subtitle">
          {{#with was}}
            was: {{.}}
          {{/with}}
          {{#with renamedFrom}}
            renamed from: {{.}}
          {{/with}}
        </div>
      {{else}}
        {{title}}
      {{/if}}
    </div>
  {{/with}}
</template>
<template name="grainDeleteButton">
  <button class="grain-button" title="Move to trash" id="deleteGrain">Move to trash</button>
</template>
<template name="grainDebugLogButton">
  <button class="grain-button" title="Show Debug Log" id="openDebugLog">Log</button>
</template>
<template name="grainBackupButton">
  <button class="grain-button" title="Download Backup" id="backupGrain">Backup</button>
</template>

<template name="grainBackupPopup">
  <h4>Download Backup</h4>
  {{#if state.showWarning }}
    <p class="warning-intro">
      Warning! Restoring this backup might not work how you expect it to.
    </p>
    <p class="warning-body">
      {{ state.showWarning }}
    </p>
  {{/if}}
  {{#if state.processing}}
    <p> Preparing backup... </p>
  {{/if}}
  {{#if state.error}}
    <p class="error">Error: {{ state.error }}</p>
  {{/if}}

  <div class="button-row">
    <button name="cancel" title="cancel">Cancel</button>
    {{#if state.processing}}
      <div class="spinner"></div>
    {{/if}}

    {{#if state.showWarning}}
      <button name="confirm" title="download backup">Download backup</button>
    {{/if}}
  </div>
</template>

<template name="grainRestartButton">
  <button class="grain-button" title="Restart App" id="restartGrain">Restart</button>
</template>

<template name="grainApiTokenButton">
  <button class="show-popup" title="Get webkey">
    Get&nbsp;Webkey
  </button>
</template>

<template name="grainApiTokenPopup">
  <h4>Webkeys</h4>
  {{#if generatedApiToken}}
    {{#if generatedApiTokenPending}}
      <p>Generating...</p>
      <p><button id="resetApiToken">Cancel</button></p>
    {{else}}
      <p>Copy this webkey and give it to the external app:</p>
        <a id="apiTokenText" class="copy-me" href="{{generatedApiToken}}">{{generatedApiToken}}</a>
      {{#if currentUser}}
        <p><button id="resetApiToken">Go back</button></p>
      {{/if}}
    {{/if}}
  {{else}}
    <p>A webkey allows you to connect an external app (e.g. a mobile app) to this app.</p>
    <p><form class="newApiToken">
    Label: <input type="text" id="api-token-petname" placeholder="e.g. 'Android app'">
    {{#with viewInfo}}
      {{#if roles}}
        Role:
        <select id="api-token-role">
          <option title="has every app permission" selected=true>all access</option>
          {{#each roles}}
            <option title={{verbPhrase.defaultText}}
                    data-obsolete={{obsolete}}>
              {{title.defaultText}}</option>
          {{/each}}
        </select>
      {{/if}}
    {{/with}}
    <button>Create</button></form></p>
    {{#if existingTokens}}
      <p>Your existing webkeys:</p>
      <ul>
      {{#each existingTokens}}
        {{#if displayToken}}
          <li>
            <span class="token-petname" data-token-id="{{_id}}">
              {{petname}} ({{dateString created}})
            </span>
            <button class="revoke-token" title="Revoke" data-token-id="{{_id}}">Revoke</button>
          </li>
        {{/if}}
      {{/each}}
      </ul>
    {{/if}}
  {{/if}}
</template>

<template name="grainShareButton">
  <button class="show-popup" title="Share access to this grain">
    Share access
  </button>
</template>

<template name="whoHasAccess">
   <img src="/people.svg">
</template>

<template name="whoHasAccessPopup">
  <h4 class="who-has-access">Who has access</h4>
  {{#if isReady}}
  <div class="tables-container">
    <h5>People</h5>
    {{#if transitiveShares.identityOwnedShares.empty}}
      {{#if existingShareTokens}}
        <p>No logged-in users have visited your links yet.</p>
      {{else}}
        {{#if transitiveShares.grainOwnedShares.empty}}
          <p>You have granted access to nobody.</p>
        {{else}}
          <p>No logged-in users have visited your links yet.</p>
        {{/if}}
      {{/if}}
    {{else}}
      <table class="people">
        {{#each transitiveShares.identityOwnedShares}}
          <tr>
            <td> {{displayName recipient}} </td>
            <td> added by
              <ul>
                {{#each dedupedShares}}
                  <li>
                    {{displayName identityId}}
                    {{#if isCurrentIdentity identityId}}
                      <button class="revoke-access" title="Revoke" data-recipient="{{../recipient}}">
                        Revoke
                      </button>
                    {{/if}}
                  </li>
                {{/each}}
              </ul>
            </td>
          </tr>
        {{/each}}
      </table>
    {{/if}}
    {{#unless transitiveShares.grainOwnedShares.empty}}
      <h5>Grains</h5>
      <table class="grains">
        {{#each transitiveShares.grainOwnedShares}}
          <tr>
            <td>{{grainTitle recipient}}</td>
            <td> added by
              <ul>
                {{#each dedupedShares}}
                  <li>
                    {{displayName identityId}}
                    {{#if isCurrentIdentity identityId}}
                      <button class="revoke-access" title="Revoke" data-recipient="{{../recipient}}">
                        Revoke
                      </button>
                    {{/if}}
                  </li>
                {{/each}}
              </ul>
            </td>
          </tr>
        {{/each}}
      </table>
    {{/unless}}

    {{#if existingShareTokens}}
      <h5>Sharing Links</h5>
      <table class="shared-links">
      {{!-- Renamed from sharing-links to shared-links due to a common adblock rule
            in https://easylist.adblockplus.org/fanboy-social.txt --}}
        {{#each existingShareTokens}}
          {{#if displayToken}}
            <tr>
              <td>
                <span class="token-petname" data-token-id="{{_id}}">
                  {{getPetname}} ({{dateString created}})
                </span>
              </td>
              <td>
                {{#if viewInfo.roles}}
                  <select class="share-token-role" data-token-id="{{_id}}">
                    {{#each indexedRoles}}
                      <option title={{title.defaultText}}
                              data-obsolete={{obsolete}}
                              selected={{hasCurrentRole ..}}>
                        {{roleText}}</option>
                    {{/each}}
                    {{#if hasCustomRole .}}
                      <option title="custom role" selected=true>
                        [has custom permissions]
                      </option>
                    {{/if}}
                  </select>
                {{/if}}
              </td>
              <td>
                <button class="revoke-token" title="Revoke" data-token-id="{{_id}}">Revoke</button>
              </td>
            </tr>
          {{/if}}
        {{/each}}
      </table>
      {{/if}}
   </div>
   {{else}}
   <img class="spinner" src="/spinner_96.gif" alt="loading">
   {{/if}}
</template>

<template name="selectRole">
  {{#with viewInfo}}
  {{#if roles}}
  <select class="share-token-role" title="select a role" disabled={{../disabled}}>
    {{#each roles}}
    <option title={{title.defaultText}}
            data-obsolete={{obsolete}}
            {{!-- We need this special attributed because apparently Meteor does not play nice
                  with HTMLOptionElement.defaultSelected. --}}
            data-default-selected={{default}}
            selected={{default}}>
      {{roleText}}</option>
    {{/each}}
  </select>
  {{/if}}
  {{/with}}
</template>

<template name="emailInviteTab">
  <form class="email-invite">
    {{#if isDemoUser}}
      <p class="demo-mode-alert">
        Sharing emails cannot be sent while in demo mode.
        Create an account to send sharing emails, or get a shareable link instead.
      </p>
    {{/if}}
    <p>
    <span class="icon icon-people"></span>
    {{> contactInputBox contacts=contacts preselectedIdentityId=preselectedIdentityId
         disabled=isDemoUser}}
    {{> selectRole viewInfo=viewInfo disabled=isDemoUser}}
    </p>
    <div>
      <textarea class="personal-message" disabled={{isDemoUser}}
                placeholder="Type a personal message (optional)..."></textarea>
    </div>
    {{#if completionState.clear}}
    <div class="button-container" role="presentation">
      {{#with invitationExplanation}}
        {{!-- Display the entire message in the hover text, in case "overflow: ellipsis" causes
              part of the message to be hidden in the main view. --}}
        <p class="invitation-explanation" title="{{.}}">{{.}}</p>
      {{/with}}
      <button disabled={{isDemoUser}}>Send</button>
    </div>
    {{/if}}
  </form>
  {{#with completionState}}
    {{#if success}}
     <p>Successfully sent.</p>
     <p><button class="reset-invite">+ Send more invites</button></p>
    {{/if}}
    {{#if pending}}
      <p>Sending...</p>
    {{/if}}
    {{#if error}}
      <p> {{error}} </p>
      <p><button class="start-over-invite">&lt;&lt; Start over</button></p>
    {{/if}}
  {{/with}}
</template>

<template name="shareableLinkTab">
  <form class="new-share-token">
    <p>
      <span class="icon icon-people"></span>
      Anyone with this link{{#if viewInfo.roles}}:{{else}} can access the grain.{{/if}}
      {{> selectRole viewInfo=viewInfo}}
    </p>
    <input type="text" class="label" placeholder="Label (optional)">
    <p class="label-explanation">
      Use a label to remind yourself to whom you sent this unique link.</p>
    {{#if completionState.clear}}
      <div class="button-container">
        <button>Create</button>
      </div>
    {{/if}}
  </form>
  {{#with completionState}}
    {{#if success}}
      <p><span class="icon icon-copy"></span> Copy this link:</p>
      <a id="share-token-text" class="copy-me" href="{{success.url}}">{{success.url}}</a>
      <p><button class="reset-share-token">+ Create another link</button></p>
    {{/if}}
    {{#if pending}}
      <p>Generating...</p>
      <p><button class="reset-share-token">Cancel</button></p>
    {{/if}}
  {{/with}}
</template>

<template name="shareWithOthers">
  <h4 class="share-with-others">Share with others</h4>
  <div class="share-tabs" role="presentation">
    <ul role="tablist">
      <li id="send-invite-tab-header" tabindex="0" role="tab" aria-controls="send-invite-tab" aria-selected="true"> Send an invite </li>
      <li id="shareable-link-tab-header" tabindex="-1" role="tab" aria-controls="shareable-link-tab" aria-selected="false"> Get shareable link </li>
    </ul>
    <div id="send-invite-tab" role="tabpanel" class="tabpanel" aria-labelledby="send-invite-tab-header" aria-hidden="false">
      {{> emailInviteTab viewInfo=grain.viewInfo title=grain.title grainId=grain.grainId }}
    </div>
    <div id="shareable-link-tab" role="tabpanel" class="tabpanel" aria-labelledby="shareable-link-tab-header" aria-hidden="true">
      {{> shareableLinkTab viewInfo=grain.viewInfo }}
    </div>
  </div>

  <div class="footer">
    <span class="icon icon-people"></span>
    <button class="who-has-access">See who has access</button>
  </div>
</template>

<template name="grainSharePopup">
  {{#if currentGrain.isOldSharingModel}}
    <p>This grain uses the old sharing model. You can share it by copy/pasting the URL from the
       location bar.</p>
    {{#if currentGrain.isOwner}}
      <p>You can upgrade this grain to the new model, but anyone with whom you shared this grain
         previously will lose access; you will have to share it with them again.</p>
      <p>Upgrading cannot be undone.</p>
      <p><button id="privatize-grain">upgrade</button></p>
    {{/if}}
  {{else}}
    {{#if incognito}}
      <p>
        You are viewing this grain anonymously.
      </p>
      {{#with currentTokenUrl}}
        <p>
          To share access, copy this link:
          <a id="share-token-text" class="copy-me" href="{{.}}">{{.}}</a>
        </p>
      {{/with}}
      <p>
        {{#if currentUser}}
          For more sharing options, you must
          <a class="open-non-anonymously" href="{{currentTokenUrl}}">
            open this grain non-anonymously
          </a>.
        {{else}}
          For more sharing options, please sign in.
        {{/if}}
      </p>
    {{else}}
      {{> shareWithOthers grain=currentGrain}}
    {{/if}}
  {{/if}}
</template>

<template name="grainPowerboxRequest">
  <button class="show-popup" title="Powerbox request">
    P
  </button>
</template>
<template name="grainPowerboxRequestPopup">
  {{>powerboxRequest . }}
</template>

<template name="grainPowerboxOffer">
  <button class="show-popup" title="Powerbox offer">
    P
  </button>
</template>
<template name="grainPowerboxOfferPopup">
  <h4>Powerbox Offer</h4>
  {{#if state.webkey}}
  <div>
    <a class="copy-me" href="{{state.webkey}}" id="powerbox-offer-url">{{state.webkey}}</a>
    <button class="dismiss">Dismiss</button>
  </div>
  {{/if}}
  {{#if state.error}}
  <div>
     Error: {{state.error}}
  </div>
  {{/if}}
</template>

<template name="grain">
  {{>sandstormTopbarItem name="title" priority=5 topbar=globalTopbar template="grainTitle"}}
  {{#sandstormTopbarItem name="grain-size" priority=5 topbar=globalTopbar}}
    {{grainSize}}
  {{/sandstormTopbarItem}}

  {{>sandstormTopbarBlockReload ""}}

  {{setGrainWindowTitle}}

  {{#if hasAccess}}
    {{>sandstormTopbarItem name="share" priority=4 topbar=globalTopbar template="grainShareButton"
        popupTemplate="grainSharePopup"}}
  {{/if}}

  {{#if displayTrashButton}}
    {{>sandstormTopbarItem name="delete" topbar=globalTopbar template="grainDeleteButton"}}
  {{/if}}

  {{#if isOwner}}
    {{>sandstormTopbarItem name="debug-log" topbar=globalTopbar template="grainDebugLogButton" data=globalTopbar}}
    {{>sandstormTopbarItem name="backup" topbar=globalTopbar template="grainBackupButton"
                           data=globalTopbar popupTemplate="grainBackupPopup"}}
    {{>sandstormTopbarItem name="restart" topbar=globalTopbar template="grainRestartButton" data=globalTopbar}}
  {{/if}}

  {{#if hasAccess}}
    {{#if displayWebkeyButton}}
        {{>sandstormTopbarItem name="webkey" topbar=globalTopbar
            template="grainApiTokenButton" popupTemplate="grainApiTokenPopup"}}
    {{/if}}
    {{#if showPowerboxRequest}}
    {{>sandstormTopbarItem name="request" topbar=globalTopbar template="grainPowerboxRequest"
          startOpenModal=true popupTemplate="grainPowerboxRequestPopup" data=powerboxRequestData
          onDismiss=cancelPowerboxRequest}}
    {{/if}}
    {{#if showPowerboxOffer}}
      {{>sandstormTopbarItem name="offer" topbar=globalTopbar template="grainPowerboxOffer"
          startOpenModal=true popupTemplate="grainPowerboxOfferPopup" data=powerboxOfferData}}
    {{/if}}
  {{/if}}
</template>

<template name="share">
  {{#if currentUser}}
    {{#with grainNotFound}}
      No grain found with ID {{.}}. Maybe you need to sign in to a different account?
    {{/with}}
  {{else}}
    You must be signed in to grant access to a grain.
  {{/if}}
</template>

<template name="_grainSpinner">
  {{!-- This is a terrible hack to center this thing. The styles shold go in css, but it's
    arguably more confusing to put them there when all they're doing is this archaic pattern to
    get a horizontally+vertically centered div --}}
  <div id="grain-loading-spinner">
    <div style="display:table-cell;vertical-align:middle;">
      <div style="margin-left:auto;margin-right:auto;text-align:center;">
        <img src="/spinner_96.gif" alt="loading">
      </div>
    </div>
  </div>
</template>
